package com.team8.upload.controller;

import com.team8.common.results.PageResult;
import com.team8.common.results.Result;
import com.team8.upload.pojo.XmlFiles;
import com.team8.upload.service.UploadService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/xml")
    public ResponseEntity<String> uploadXml(@RequestParam("file") MultipartFile file){
        String url = this.uploadService.upload(file);
        if (StringUtils.isBlank(url) || url.contains("bad")) {
            return ResponseEntity.badRequest().build();
        }
        amqpTemplate.convertAndSend("as.xmlparse.exchange", "xml.parse", url);
        return ResponseEntity.status(HttpStatus.CREATED).body(url);
    }
    @PostMapping("/xmls")
    public ResponseEntity<Result> uploadXmls(@RequestParam("files") MultipartFile[] files){

        StringBuilder urls = new StringBuilder("");
        for(MultipartFile file : files){
            String url = this.uploadService.upload(file);
            if (StringUtils.isBlank(url) || url.contains("bad") ) {
                return ResponseEntity.ok(new Result(400, url));
            }
            // 交换机    routing key   消息
            amqpTemplate.convertAndSend("as.xmlparse.exchange", "xml.parse", url);

            urls.append(url + "\n");
        }

        return ResponseEntity.ok(new Result(200, urls.toString()));
    }

    @GetMapping("/updateXmlFileStatus")
    public ResponseEntity<Boolean> updateXmlFileStatus(@RequestParam("filename") String filename, @RequestParam("status")String status){
        Boolean b = uploadService.updateXmlFileStatus(filename, status);
        return ResponseEntity.ok(b);
    }

    @GetMapping("/xmlinfos")
    public ResponseEntity<PageResult<XmlFiles>> getXmlInfos(@RequestParam("page") Integer page, @RequestParam("size") Integer size){

        PageResult<XmlFiles> xmlFiles = uploadService.getXmlInfos(page, size);
        System.out.println(xmlFiles.getTotal());
        return ResponseEntity.ok(xmlFiles);
    }
}